<?php

class Controller_Shop extends Controller_Website
{

    public function before() {
        parent::before();
        $this->mod = Model::factory('directory');
        $this->man = Model::factory('manager');
        $this->section = 'shop';
        $this->itemsPerPage = 8; //<-кількість елементів на 1 сторінці
        $this->template->controller=Request::$controller;
//        $this->addStyle('/styles/cusel.css');
//        $this->addScript('/scripts/pgscroll.js');
    }

	public function actionIndex()
	{
        $this->response->redirect(Request::$controller.'category/');
	}


    public function actionCategory($category=null,$subcategory=null,$page=1,$paginator=null)
    {

        $page = (int) strtolower(trim(strip_tags($page - 1)));
        $this->template->content = new View('woman/index');
        $this->template->content->controller=$this->template->controller=Request::$controller;
        $this->template->content->images=$images=$this->man->getImagesParrentKey($this->section); //<-Масив картинок для секції
        foreach ($images as $image){
            foreach ($image as $logoimage){
                if ($logoimage['select1']==1){
                    $logoImage[$logoimage['itemId']] = $logoimage;
                    break;
                }else{
                    $logoImage[$logoimage['itemId']] = $logoimage;
                }
            }
        }
        $this->template->content->logoImg=$logoImg=isset($logoImage)?$logoImage:array();
        if($category<>null&&$subcategory==null){// Коли зайшов в першу категрію
            $this->template->categories=$categories=$this->man->getChidrenCategoriesByAlias($category,$this->section);
            $this->template->activecategory=$this->template->content->activecategory=ucfirst($category);
            isset($categories[0]['alias'])?$this->response->redirect(Request::$controller.strtolower(substr(__FUNCTION__, 6)).'/'.$category.'/'.$categories[0]['alias'].'/'):'';

        }elseif($category<>null&&$subcategory<>null&&$paginator){
            $this->template->categories=$this->man->getChidrenCategoriesByAlias($category,$this->section);
            $this->template->activecategory=$activecategory=$this->template->content->activecategory=ucfirst($category);
            $this->template->activecategorySecond=$activecategorySecond=$this->template->content->activecategorySecond=ucfirst($subcategory);
            $this->template->content->items=$items=$this->man->getCategoryItemsByAlias($subcategory, $this->section, $page, $this->itemsPerPage); //<-Виведення елементів по аліасу з лімітом
            $activecategorySecond=strtolower(isset($activecategorySecond)?$activecategorySecond.'/':'');
            $activecategory=strtolower(isset($activecategory)?$activecategory.'/'.$activecategorySecond:'');
            if(isset($items)){foreach($items as $item){
                if((isset($logoImg[$item['id']]))){
                    $logoimg='/content/directory/images/shop/shopItemPreview/'.substr($logoImg[$item['id']]['alias'],0, 1).'/'.$logoImg[$item['id']]['alias'].'.jpg';
                }else{
                    $logoimg='/images/no_item_image.jpg';
                }
                echo'<a href="'.Request::$controller.'item/'.$item['alias'].'/'.$activecategory.'">
                            <div class="product_item">
                                <img src="'.$logoimg.'"/>
                                <div class="product_item_desc">
                                    <span>'.$item['name'].'</span>
                                    <div class="yellow_link">'.mb_substr($item['price'],0,-3).' грн</div>
                                </div>
                            </div>
                        </a>';
            }}
            exit();

        }elseif($category<>null&&$subcategory<>null){// Коли зайшов в другу категрію
            $this->addScript('/scripts/pgscroll.js');
            $this->template->categories=$this->man->getChidrenCategoriesByAlias($category,$this->section);
            $this->template->activecategory=$this->template->content->activecategory=ucfirst($category);
            $this->template->activecategorySecond=$this->template->content->activecategorySecond=ucfirst($subcategory);
            $this->template->content->items=$items=$this->man->getCategoryItemsByAlias($subcategory, $this->section, $page, $this->itemsPerPage); //<-Виведення елементів по аліасу з лімітом
//            $this->autoRender = false;
//            $this->response->setHeader('Content-Type', 'application/json');
//            if (isset($items[0])) {
//                $paginatorURL = '/'.$this->section.'/' . strtolower(substr(__FUNCTION__, 6)) . '/' . $category.'/'.$subcategory; //формуємо урл для пагінатора
//                $this->template->content->paginatorNavigate = $this->man->paginatorNavigator($items[0]['parentId'], $this->section, $this->itemsPerPage, $page, $paginatorURL);
//            }

        }else{// Коли зайшов на головну сторінку магазину
            $this->template->content->items=$items=$this->man->getItemsLimit($this->section,$this->itemsPerPage);
        }
    }
    public function actionPage($category=null,$subcategory=null, $page=1)
    {
        $page = (int) strtolower(trim(strip_tags($page - 1)));
        $this->template->content = new View('woman/index');
        $this->template->content->controller=$this->template->controller=Request::$controller;
        $this->template->content->images=$images=$this->man->getImagesParrentKey($this->section); //<-Масив картинок для секції
        foreach ($images as $image){
            foreach ($image as $logoimage){
                if ($logoimage['select1']==1){
                    $logoImage[$logoimage['itemId']] = $logoimage;
                    break;
                }else{
                    $logoImage[$logoimage['itemId']] = $logoimage;
                }
            }
        }
        $this->template->content->logoImg=isset($logoImage)?$logoImage:array();
        if($category<>null&&$subcategory==null){// Коли зайшов в першу категрію
            $this->template->categories=$categories=$this->man->getChidrenCategoriesByAlias($category,$this->section);
            $this->template->activecategory=$this->template->content->activecategory=ucfirst($category);
            isset($categories[0]['alias'])?$this->response->redirect(Request::$controller.strtolower(substr(__FUNCTION__, 6)).'/'.$category.'/'.$categories[0]['alias'].'/'):'';
        }elseif($category<>null&&$subcategory<>null){// Коли зайшов в другу категрію
            $this->addScript('/scripts/pgscroll.js');
            $this->template->categories=$this->man->getChidrenCategoriesByAlias($category,$this->section);
            $this->template->activecategory=$this->template->content->activecategory=ucfirst($category);
            $this->template->activecategorySecond=$this->template->content->activecategorySecond=ucfirst($subcategory);
            $this->template->content->items=$items=$this->man->getCategoryItemsByAlias($subcategory, $this->section, $page, $this->itemsPerPage); //<-Виведення елементів по аліасу з лімітом


                $activecategorySecond=strtolower(isset($activecategorySecond)?$activecategorySecond.'/':'');
                $activecategory=strtolower(isset($activecategory)?$activecategory.'/'.$activecategorySecond:'');
                if(isset($items)){foreach($items as $item){
                    if((isset($logoImg[$item['id']]))){
                        $logoimg='/content/directory/images/shop/shopItemPreview/'.substr($logoImg[$item['id']]['alias'],0, 1).'/'.$logoImg[$item['id']]['alias'].'.jpg';
                    }else{
                        $logoimg='';
                    }
                    echo'<a href="'.Request::$controller.'item/'.$item['alias'].'/'.$activecategory.'">
                            <div class="product_item" style="background: url('.$logoimg.') no-repeat top">
                                <div class="product_item_desc">
                                    <span>'.$item['name'].'</span>
                                    <div class="yellow_link">'.$item['price'].'</div>
                                </div>
                            </div>
                        </a>';
                }}
                exit();
//                        $this->autoRender = false;
//                        $this->response->setHeader('Content-Type', 'application/json');
            if (isset($items[0])) {
                $paginatorURL = '/'.$this->section.'/' . strtolower(substr(__FUNCTION__, 6)) . '/' . $category.'/'.$subcategory; //формуємо урл для пагінатора
                $this->template->content->paginatorNavigate = $this->man->paginatorNavigator($items[0]['parentId'], $this->section, $this->itemsPerPage, $page, $paginatorURL);
            }
        }else{// Коли зайшов на головну сторінку магазину
            $this->template->content->items=$items=$this->man->getItemsLimit($this->section,$this->itemsPerPage);
        }
    }
    public function actionItem($alias=null,$category=null,$subcategory=null)
    {
        $this->template->content = new View('item/index');
        $this->template->content->category=$category;
        $this->template->content->subcategory=$subcategory;
        $this->template->content->item=$item=$this->mod->getItemByAlias($alias,$this->section);
        
        $suggestion = $this->manager->getSuggestions($item['id'],$item['parentId']);
        $this->template->content->suggestion=$suggestion;
        
        $colors=explode(",", $item['note2']);
        $aviableColors=$this->man->getColors('colors');
        foreach($colors as $color){
            $colorList[$color]=isset($aviableColors[$color])?$aviableColors[$color]:array('name'=>$color);
            isset($colorList[$color]['alias'])?$colorList[$color]['alias']:$colorList[$color]['alias']='none';
        }
        $this->template->content->colorList=$colorList;
        $aviableSizes=$this->man->getColors('sizes');
        $sizes=explode(",", $item['note1']);
        foreach($sizes as $size){
            $sizeList[$size]=isset($aviableSizes[$size])?$aviableSizes[$size]:array('name'=>$size);
            isset($sizeList[$size]['alias'])?$sizeList[$size]['alias']:$sizeList[$size]['alias']='none';
        }
        $this->template->content->sizeList=$sizeList;
        $this->template->content->images=$images=$this->mod->getItemImages($item['id'],$this->section);
//        system::dump(current($images));exit();
        foreach($images as $image){
            if($image['select1']==1){
                $this->template->content->mainImage=$image;break;
            }
        }
    }
    public function actionSend(){
        $this->autoRender = FALSE;

        if(Request::$isAjax)
        {
            $email = Request::get('email');
            $message = Request::get('message');
            $message = strip_tags(trim($message));
            $link= Request::get('link');

            $msg =  '';
            $msg .= 'You have new message from:' . "\n\n";
            $msg .= 'Email: '.$email . "\n";
            $msg .= 'Message:' . "\n" . $message."\n";
            $msg .= 'For details please visit '.$link. "\n";

            if(Validate::email($email) &&$message !== '')
            {
                Mailer::sendMail($email, 'From your friend', $msg, $this->settings['title'].'<noreply@'.$_SERVER['HTTP_HOST'].'>');

            }
            else
            {
                echo 'Check form and try ag';
            }
        }

    }
}